package face.pay.wx.controller.service.impl;

import face.pay.dao.*;
import face.pay.entity.CpnCardDetailInfo;
import face.pay.entity.CpnOemWxInfo;
import face.pay.entity.CpnWxAppInfo;
import face.pay.entity.OemInfo;
import face.pay.wx.config.SystemConfig;
import face.pay.wx.controller.service.IGetCouponService;
import face.pay.util.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import weixin.popular.api.SnsAPI;
import weixin.popular.bean.sns.SnsToken;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GetCouponServiceImpl implements IGetCouponService {

    @Autowired
    SystemConfig systemConfig;

    @Autowired
    OemInfoDao oemInfoDao;

    @Autowired
    CpnCardDetailInfoDao cpnCardDetailInfoDao;

    @Override
    public String getCpn(String cpn_auth_code, Model model, HttpServletRequest request) throws Exception {
        String domain =   request.getServerName();
        log.info("访问域名："+domain);
        log.info("cpn_auth_code："+cpn_auth_code);
        CpnCardDetailInfo cpnCardDetailInfo =  this.cpnCardDetailInfoDao.getByCpnCode(cpn_auth_code);

        if(cpnCardDetailInfo!=null){
           Integer oemId  =   cpnCardDetailInfo.getOemId();

            OemInfo oemInfo =  this.oemInfoDao.getOemInfoById(oemId);

            if(oemInfo!=null){

                String appid =oemInfo.getAppId();
                String auth_path=systemConfig.getCpnAuthPath();

                String redirect_uri = "http://"+domain+"/"+auth_path;
                String url =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}&connect_redirect=1#wechat_redirect";
                url =  MessageFormat.format(url,appid,redirect_uri,cpn_auth_code);
                return  url;
            }else {
                throw new Exception("域名未注册");
            }

        }else {
            throw new Exception("优惠券不存在");
        }


    }

    @Override
    public Boolean cpnAuth(String code, String state, Model model, HttpServletRequest request) {

        Map<String,Object> map =  new HashMap<>();

        String errorMessage = "";

        Boolean isSuccess = false;

        String cpn_auth_code = state;

        String domain =   request.getServerName();
        log.info("cpnAuth 访问域名："+domain);

        CpnCardDetailInfo cpnCardDetailInfo =  this.cpnCardDetailInfoDao.getByCpnCode(cpn_auth_code);

        if(cpnCardDetailInfo!=null) {

            Integer oemId = cpnCardDetailInfo.getOemId();
            OemInfo oemInfo =  this.oemInfoDao.getOemInfoById(oemId);
            if(oemInfo!=null){

                log.info("获取oem服务商优惠券兑换 微信配置信息："+oemInfo.toString());

                log.info("cpn_auth_code："+cpn_auth_code);
                /**
                 * 解码 cpnAuthCode
                 */
                if(StringUtils.isNotBlank(cpn_auth_code)){

                    Integer status = cpnCardDetailInfo.getStatus();

                    if(new Integer(0).equals(status)){
                        String appid = oemInfo.getAppId();
                        String secret = oemInfo.getSecret();
                        SnsToken snsToken =  SnsAPI.oauth2AccessToken(appid,secret,code);
                        String openId = snsToken.getOpenid();
                        cpnCardDetailInfo.setOemOpenId(openId);
                        cpnCardDetailInfoDao.upOpenId(cpnCardDetailInfo);
                        isSuccess = true;
                    }else {
                        errorMessage = "优惠券已兑换";
                    }
                }else {
                    errorMessage="优惠券cpn_auth_code错误";
                }
            }else {
                errorMessage = "获取用户资料失败";
            }

        }



        model.addAttribute("errorMessage",errorMessage);
        model.addAttribute("isSuccess",isSuccess);

        return  isSuccess;
    }
}
